<?php

// php -S localhost:8080 xxx.php

// HTTP methods
const AVAILABLE_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];

if (!in_array($_SERVER['REQUEST_METHOD'], AVAILABLE_METHODS)) {
    http_response_code(400);
    echo '';
    return;
}

// Parse JSON
if($_SERVER['CONTENT_TYPE'] == 'application/json') {
    $_POST = \json_decode(file_get_contents('php://input'), true) ?? [];
    file_put_contents("php://stdout", "\nRequested: $_POST");
}


// Router
$response = match (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)) {
    '/'          => 'Hello World!',
    '/get'       => json_encode($_GET),
    '/post'      => json_encode($_POST),
    '/headers'   => json_encode(getallheaders()),
    '/method'    => $_SERVER['REQUEST_METHOD'],
    '/server_ip' => $_SERVER['SERVER_ADDR'],
    '/ip'        => $_SERVER['REMOTE_ADDR'],
    '/cookies'   => cookies(),
    '/upload'    => json_encode($_FILES),
    '/phpinfo'   => php_info(),

    default => (static function (): string {
        http_response_code(404);
        return '404 Not Found';
    })(),
};

echo $response;


function cookies(): string
{
    if ($_GET === []) {
        return json_encode($_COOKIE);
    }

    if (isset($_GET['set'])) {
        foreach ($_GET['set'] as $name => $value) {
            setcookie($name, $value);
        }
        return json_encode($_COOKIE);
    }

    if (isset($_GET['delete'])) {
        foreach ($_GET['delete'] as $name) {
            if (isset($_COOKIE[$name])) {
                unset($_COOKIE[$name]);
                setcookie($name, '', -1);
            }
        }
        return json_encode($_COOKIE);
    }
}

function php_info(): string
{
    ob_start();
    phpinfo();
    return ob_get_clean();
}